package main

import "fmt"

//type ListNode struct {
//	Val  int
//	Next *ListNode
//}

//// 创建一个新的链表节点
//node1 := &ListNode{Val: 1}
//node2 := &ListNode{Val: 2}
//node3 := &ListNode{Val: 3}
//
//// 将节点连接起来形成链表
//node1.Next = node2
//node2.Next = node3

func removeNthFromEnd(head *ListNode, n int) *ListNode {
	// 创建一个虚拟节点，指向链表头
	dummy := &ListNode{0, head}

	// 初始化两个指针，分别指向虚拟节点
	first, second := dummy, dummy

	// 让第一个指针先向前移动 n+1 步
	for i := 0; i <= n; i++ {
		first = first.Next
	}

	// 然后让两个指针同时向前移动，直到第一个指针到达链表末尾
	for first != nil {
		first = first.Next
		second = second.Next
	}

	// 删除第二个指针所指向的节点
	second.Next = second.Next.Next

	// 返回链表头
	return dummy.Next
}

func main() {
	l1 := &ListNode{1, &ListNode{2, &ListNode{3, &ListNode{4, &ListNode{5, nil}}}}}
	result1 := removeNthFromEnd(l1, 2)
	fmt.Println("Example 1: ")
	for result1 != nil {
		fmt.Print(result1.Val, " ")
		result1 = result1.Next
	}
	fmt.Println()

	// 示例 2
	l2 := &ListNode{1, &ListNode{2, nil}}
	result2 := removeNthFromEnd(l2, 1)
	fmt.Println("Example 2: ")
	for result2 != nil {
		fmt.Print(result2.Val, " ")
		result2 = result2.Next
	}
	fmt.Println()
}
